<template>
  <div class="content" v-loading="loading">
    <el-form
      ref="form"
      :disabled="type === '0'"
      :model="form"
      :rules="rules"
      label-width="106px"
    >
      <el-row :gutter="40">
        <el-col :span="12">
          <el-form-item label="主题编码" prop="subjectCode" v-if="form.id">
            <el-input v-model="form.subjectCode" placeholder="请输入主题编码" disabled/>
          </el-form-item>
          <el-form-item label="主题名称" prop="subjectName">
            <el-input v-model="form.subjectName" placeholder="请输入主题名称"/>
          </el-form-item>
          <el-form-item label="系统类型" prop="systemType">
            <template v-if="!form.id">
              <el-select v-model="form.systemType"
                         placeholder="请选择系统类型"
                         style="width: 100%;"
                         @change="changeSysType"
              >
                <el-option
                  v-for='item in systemTypeOptions'
                  :key='item.value'
                  :label='item.label'
                  :value="item.value"
                />
              </el-select>
            </template>
            <template v-if="form.id">
              <el-select v-model="form.systemType"
                         style="width: 100%;"
                         disabled
              >
                <el-option
                  v-for='item in systemTypeOptions'
                  :key='item.value'
                  :label='item.label'
                  :value="item.value"
                />
              </el-select>
            </template>
          </el-form-item>
          <el-form-item label="关联网点" prop="branchCode">
            <treeselect
              v-model="form.branchCode"
              :options="branchDataOptions"
              :normalizer="branchNormalizer"
              :show-count="true"
              placeholder="选择主题关联网点"
              class="custom-input-width"
              @select="handleBranchChange"
              noOptionsText="暂无选项"
              noResultsText="没有匹配的搜索结果"
              :disabled="type === '0'"
            />
          </el-form-item>
          <el-form-item label="父主题" prop="parentSubjectCode">
            <treeselect
              ref="ParentSubjectTree"
              class="custom-input-width"
              v-model="form.parentSubjectCode"
              :options="subjectsTreeOptions"
              :normalizer="subjectNormalizer"
              :show-count="true"
              placeholder="选择父级主题"
              noOptionsText="暂无选项"
              :disabled="type === '0'"
            />
          </el-form-item>
          <el-form-item label="列表展示方式" prop="linkTo">
            <el-select v-model="form.linkTo" placeholder="列表展示方式" style="width: 100%">
              <el-option
                v-for="item in linkToOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
                <div style="display: flex;justify-content: space-between;align-items: center">
                  {{item.label}}
                  <a
                    :href="'/SelfServiceManagementSite/homeLayoutPreview/' + item.value + '.png'"
                    target="_blank"
                    style="margin-left:10px;font-size: 16px;padding:0 10px"
                  >
                    <i class="el-icon-view"></i>
                  </a>
                </div>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="同级内排序号" prop="sort">
            <el-input-number
              v-model="form.sort"
              size="small"
              :min="0"
              :precision="0"
              label="同级内排序号"
            />
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" placeholder="请输入备注"/>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="主题图标" prop="subjectLogo">
            <UFileUpload
              :value="form.subjectLogo"
              :limit="1"
              :fileSize="2"
              @input="imageUploadSuccess"
            />
          </el-form-item>
          <el-form-item label="主题激活图标" prop="subjectActiveLogo">
            <UFileUpload
              :value="form.subjectActiveLogo"
              :limit="1"
              :fileSize="2"
              @input="imageActivationSuccess"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div v-if="type != '0'" class="btn-wrap">
      <el-button type="primary" @click="submitForm" :disabled="disabledSubmitBtn" style="width: 200px">
        确 定
      </el-button>
    </div>

  </div>
</template>

<script>
import {addSubject, getSubject, selectTCfgSubjectByBranchCode, updateSubject} from "@/api/items/subject";
import {handleTree} from "@/utils/ruoyi";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "SubjectInfoForm",
  components: {Treeselect},
  props: {
    subjectData: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      loading: false,
      // 表单参数
      form: {
        id: null,
        subjectCode: null,
        subjectName: null,
        branchCode: null,
        branchName: null,
        parentSubjectCode: null,
        systemType: null,
        linkTo: null,
        subjectLogo: null,
        sort: 0,
        remark: null,
        subjectActiveLogo: null
      },
      // 表单校验
      rules: {
        subjectName: [
          {required: true, message: "主题名称不能为空", trigger: "blur"}
        ],
        systemType: [
          {required: true, message: "系统类型不能为空", trigger: "blur"}
        ],
        branchCode: [
          {required: true, message: "网点编码不能为空", trigger: "blur"}
        ],
        parentSubjectCode: [
          {required: true, message: "父主题不能为空", trigger: "blur"}
        ]
      },
      // 添加弹窗主题树选项数据
      subjectsTreeOptions: [],
      systemTypeOptions: [
        {label: "门户", value: 1},
        {label: "填表系统", value: 2},
        {label: "表单电子范例系统", value: 3},
        {label: "智能查询系统", value: 4},
        {label: "填表验收系统", value: 5},
        {label: "导办系统", value: 6}

      ],
      // 当前页面表单显示类型 0：查看 1：修改 2：新增
      type: '',
      linkToOptions: [
        {label: "热门1布局", value: 'HotLayoutOne'},
        {label: "热门2布局", value: 'HotLayoutTwo'},
        {label: "瀑布流方式展示下一级主题及其事项", value: 'ChildSubjectWithAffairLayout'},
        {label: "两级子主题和事项组成的页面", value: 'ComplexChildSubjectWithAffairLayout'},
        {label: "列表展示下一级事项", value: 'ChildAffairLayout'},
        {label: "列表展示一链办或下一级事项（大图标）", value: 'ChildAffairBigIconLayout'},
        {label: "列表展示下一级主题（大图标）", value: 'ChildSubjectLayout'},
        {label: "列表展示下一级主题（小图标）", value: 'ChildSubjectSmallIconLayout'},
        {label: "我要办事布局", value: 'HandleAffairs'},
        {label: "带tab的主题列表", value: 'TabsSubjectList'}
      ]
    }
  },
  computed: {
    // 网点树形数据
    branchDataOptions() {
      return this.$store.state.device.branchDataOptions || []
    },
    disabledSubmitBtn() {
      // 修改时主题信息时如果没有修改数据 禁用确定按钮
      if (this.form.id && !this.checkedHasChange()) return true
      return false
    },
  },
  methods: {
    /*根据id查找祖级id
@params { Array } sourceData 要查找的数据源
@params { Number/String } id 查找的id
@params { Boolean } includeSelf 返回值是否包含自己id
@return { String } id 祖级id拼接","字符串
*/
    findAncestorsId(sourceData, subjectCode, includeSelf = false) {
      const find = (array, subjectCode) => {
        //储存父级id
        let stack = [];
        //是否继续循环
        let going = true;

        let walker = (array, subjectCode) => {
          array.forEach(item => {
            if (!going) return;
            stack.push(item['subjectCode']);
            if (item['subjectCode'] == subjectCode) {
              going = false;
            } else if (item['children']) {
              walker(item['children'], subjectCode);
            } else {
              stack.pop();
            }
          });
          if (going) stack.pop();
        }

        walker(array, subjectCode);

        // 返回包含自身id的拼接字符串
        if (includeSelf) return stack.join(',');

        // 去掉自身id的拼接字符串
        return stack.slice(0, stack.length - 1).join(',');
      }
      return find(sourceData, subjectCode);
    },
    // 网点选择选时触发
    handleBranchChange(value) {
      this.form.branchcName = value.branchName;
      this.form.parentSubjectCode = null;
      // 根据网点编码获取包含的主题
      this.getIncludedSubject(value.branchCode);
    },
    // 根据网点编码获取包含的主题
    getIncludedSubject(branchCode) {
      this.subjectsTreeOptions = [];
      this.loading = true;
      selectTCfgSubjectByBranchCode({
        branchCode,
        systemType: this.form.systemType
      }).then(response => {
        // 构造树形数据
        const children = handleTree(response.rows, "subjectCode", "parentSubjectCode");
        // 在所有选项外面加上一个“所有父主题”选项,解决当网点parentId为0，修改时因为parentId=0没有数据导致无法自动选中
        this.subjectsTreeOptions = [{
          children,
          subjectCode: '0',
          subjectName: '无',
        }]
      }).finally(() => {
        this.loading = false;
      })
    },
    /** 转换网点树形图数据结构 */
    branchNormalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.branchCode,
        label: node.branchName,
        children: node.children || undefined
      };
    },
    /** 转换主题区域树形图数据结构 */
    subjectNormalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.subjectCode,
        label: node.subjectName,
        children: node.children || undefined
      };
    },
    // 图片上传成功
    imageUploadSuccess(imgUrl) {
      this.form.subjectLogo = imgUrl;
    },
    imageActivationSuccess(imgUrl) {
      this.form.subjectActiveLogo = imgUrl;
    },
    // 检查表单是否有改变
    checkedHasChange() {
      return JSON.stringify(this.form) !== JSON.stringify(this.subjectData);
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const subjectAncestors = this.findAncestorsId(this.subjectsTreeOptions, this.form.parentSubjectCode, true);
          this.form.ancestors = subjectAncestors
          // console.log(this.form, 'this.form')
          if (this.id) {
            if (this.form.subjectCode === this.form.parentSubjectCode) {
              return this.$modal.confirmAlert('不允许选自己作为父主题！')
            }
            // 获取主题祖级列表
            updateSubject(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.$emit('getSubjectInfo');
            });
          } else {
            addSubject(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.$emit('getSubjectInfo', response.data);
              // 修改页面编辑模式 0：查看 1：修改 2：新增
              this.type = '1';
              this.$router.push({
                name: 'SubjectDetail',
                query: {
                  id: response.data.id,
                  // type 0：查看 1：修改 2：新增
                  type: '1'
                }
              })
            });
          }
        }
      });
    },
    changeSysType(e) {
      this.$emit('changeValue', e)
      // 如果已选择网点，因为系统类型变了，父主题选项也要重新获取
      if(this.form.branchCode){
        // 清空已选父主题
        this.form.parentSubjectCode = undefined
        // 获取同系统主题
        this.getIncludedSubject(this.form.branchCode)
      }
    }
  },
  watch: {
    form: {
      deep: true,
      handler: function (val) {
        // 清空网点时，父主题和选项也需要跟着清空
        if (!val.branchCode) {
          this.form.parentSubjectCode = null;
          this.subjectsTreeOptions = [{
            subjectCode: 0,
            subjectName: '无',
          }]
        }
      }
    },
    subjectData: {
      immediate: true,
      handler(newValue) {
        // 存在id
        if (newValue.id) {
          this.form = JSON.parse(JSON.stringify(newValue));
          this.id = newValue.id;
          // 根据网点编号获取主题选项
          this.getIncludedSubject(newValue.branchCode);
        }
      }
    }
  },
  mounted() {
    const {id, type} = this.$route.query;
    this.id = id;
    // 编辑类型 0：查看 1：修改 2：新增
    this.type = type;
  },
}
</script>

<style lang="scss" scoped>
.content {
  box-sizing: border-box;
  width: 100%;
  max-width: 1000px;
  height: 100%;
  padding: 10px 0;

  .btn-wrap {
    margin-top: 10px;
    text-align: center;
    margin-bottom: 50px;
  }
}
</style>
